package com.harvest.scientific.ladder.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.CountDownTimer
import android.text.Html
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.adpater.BaseMultiItemAdapter
import com.harvest.scientific.ladder.databinding.MultiNoOrderItemLayoutBinding
import com.harvest.scientific.ladder.databinding.OrderSuccessDialogBinding
import com.harvest.scientific.ladder.databinding.OrderSuccessItemLayoutBinding
import com.harvest.scientific.ladder.ext.asLifecycleOwner
import com.harvest.scientific.ladder.ext.dp2px
import com.harvest.scientific.ladder.ext.formatToNumber
import com.harvest.scientific.ladder.ext.getString
import com.harvest.scientific.ladder.ext.launch
import com.harvest.scientific.ladder.ext.setMaterialDrawable
import com.harvest.scientific.ladder.res.MentalDrinkRes
import com.harvest.scientific.ladder.res.StrongPensionQuilt
import com.harvest.scientific.ladder.util.LogUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import okhttp3.internal.EMPTY_BYTE_ARRAY
import java.util.ResourceBundle

/**
 * @author：zenglingwen
 * @date：2024-06-11 23:25
 * @desc：
 */


class OrderSuccessAdapter(datas: ArrayList<StrongPensionQuilt>, val fromType: Int = 0) : BaseMultiItemAdapter<StrongPensionQuilt>(datas) {

    class OrderSuccessItemHolder(val viewBinding: OrderSuccessItemLayoutBinding): RecyclerView.ViewHolder(viewBinding.root)
    init {
        addItemType(0, object : OnMultiItemAdapterListener<StrongPensionQuilt, OrderSuccessItemHolder> {
            override fun onCreate(
                context: Context,
                parent: ViewGroup,
                viewType: Int
            ): OrderSuccessItemHolder {

                val viewBinding =
                    OrderSuccessItemLayoutBinding.inflate(LayoutInflater.from(context), parent, false)
                return OrderSuccessItemHolder(viewBinding)
            }

            @SuppressLint("SetTextI18n")
            override fun onBind(holder: OrderSuccessItemHolder, position: Int, item: StrongPensionQuilt?) {
                item?.let {

                    val binding = holder.viewBinding
                    binding.huankuanInfoContainer.updatePadding(left = if (fromType == 1) dp2px(13f).toInt() else dp2px(5f).toInt())
                    binding.huankuanInfoContainer.setMaterialDrawable(dp2px(1f), if (fromType == 1) Color.parseColor("#F2F3F9") else Color.parseColor("#F1F3FF"))
//                binding.huankuanInfoContainer.setMaterialDrawable(dp2px(2f), context.getColor(R.color.color_F1F3FF))
                    binding.title.text = "${position + 1}/${items.size}"
                    if (item.suddenHerselfScottishHardworkingCathedral.values.isNotEmpty()) {
                        binding.huankuanTimeTv.text = Html.fromHtml(context.getString(R.string.date_du_1er_chelonnement, item.suddenHerselfScottishHardworkingCathedral.values.first()))
                    } else {
                        binding.huankuanTimeTv.text = ""
                    }

                    binding.huankuanTime.text = item.dailyAthleteUnfortunateCarefulPassport

                    if (item.ripeFrench.values.isNotEmpty()) {
                        binding.huankuanJineTv.text = Html.fromHtml(context.getString(R.string.montant_du_2e_chelonnement, item.ripeFrench.values.first()))
                    } else {
                        binding.huankuanJineTv.text = ""
                    }
                    binding.huankuanJine.text = context.getString(R.string.xof, item.thankfulRainyLung.toString().formatToNumber())

                }
            }

        })
    }
}

class OrderSuccessDialog(val cxt: Context, val datas: ArrayList<StrongPensionQuilt>, val onDismiss: () -> Unit): CommonDialog<OrderSuccessDialogBinding>(cxt) {
    override fun initView() {
        super.initView()
        _binding.contentContainer.setMaterialDrawable(
            context.resources.getDimension(R.dimen.dp_10),
            Color.WHITE
        )

        initOrderItemList()

        countDown(time = 5, next = {
            _binding.countDownTv.text = "${it}S"
            if (it == 0){
                dismissDialog()
            }

        })
        setOnDismissListener {
            onDismiss.invoke()
        }

    }

    private fun initOrderItemList() {
        _binding.recyclerview.run {
            layoutManager = LinearLayoutManager(cxt)
            adapter = OrderSuccessAdapter(datas)
        }
    }

    private fun countDown(
        timeMillis: Long = 1000,//默认时间间隔 1 秒
        time: Int = 60,//默认时间为 3 秒
        start: ((scope: CoroutineScope) -> Unit)? = null,
        end: (() -> Unit)? = null,
        next: ((time: Int) -> Unit)? = null,
        error: ((msg: String?) -> Unit)? = null
    ) {
        cxt.launch {
            flow {
                (time downTo 0).forEach {
                    emit(it)
                    delay(timeMillis)
                }
            }.onStart {
                start?.invoke(this@launch)
            }.onCompletion {
                end?.invoke()
            }.catch {
                error?.invoke(it.message)
            }.collect {
                next?.invoke(it)
            }
        }
    }
}